import type { FC } from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import { DatePicker } from 'antd';
import type { Moment } from 'moment';
import moment from 'moment';
const { RangePicker } = DatePicker;

const CommonDateRangePicker: FC<any> = (props) => {
  const { value, onChange } = props;
  const [chosenDate, setChosenDate] = useState<any>([]); // 已选择的时间

  const handleChange = (val: Moment[]) => {
    onChange && onChange(val);
  };

  const range = (start: number, end: number) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };

  const disabledTime = (activeTime: any, type: string) => {
    if (!chosenDate) return {};

    const compareTime = type === 'start' ? chosenDate[1] : chosenDate[0];
    const nowHours = moment(compareTime).hours(); //0~23
    const nowMinutes = moment(compareTime).minutes(); //0~59
    const nowSeconds = moment(compareTime).seconds(); //0~59

    if (type === 'end') {
      if (activeTime && compareTime && moment(activeTime).date() === moment(compareTime).date()) {
        return {
          disabledHours: () => range(0, nowHours),
          disabledMinutes: () =>
            moment(activeTime).hour() === moment(compareTime).hour() ? range(0, nowMinutes) : [],
          disabledSeconds: () =>
            moment(activeTime).hour() === moment(compareTime).hour() &&
            moment(activeTime).minutes() === moment(compareTime).minutes()
              ? range(0, nowSeconds)
              : [],
        };
      }
    } else if (type === 'start') {
      if (activeTime && compareTime && moment(activeTime).date() === moment(compareTime).date()) {
        return {
          disabledHours: () => range(nowHours + 1, 24),
          disabledMinutes: () =>
            moment(activeTime).hour() === moment(compareTime).hour()
              ? range(nowMinutes + 1, 60)
              : [],
          disabledSeconds: () =>
            moment(activeTime).hour() === moment(compareTime).hour() &&
            moment(activeTime).minutes() === moment(compareTime).minutes()
              ? range(nowSeconds + 1, 60)
              : [],
        };
      }
    }

    return {};
  };

  useEffect(() => {
    if (value) {
      setChosenDate(value.map((o: string) => moment(o)));
    }
  }, [value]);

  return (
    <RangePicker
      {...props}
      disabledTime={disabledTime}
      onCalendarChange={(val) => {
        setChosenDate(val);
      }}
      onChange={handleChange}
    />
  );
};

export default CommonDateRangePicker;
